<template>
  <span class="form-generator-drawer">
    <span @click="openDrawer">
      <slot />
    </span>
    <el-drawer :visible.sync="drawer" :with-header="false" size="100%" direction="ttb" append-to-body>
      <FormGenerator v-if="drawer" ref="FormGenerator" @updateForm="updateForm">
        <template #title="slotProps">
          <el-button type="text" icon="el-icon-document-checked" @click="saveFormConfig(slotProps)">
            保存
          </el-button>
          <el-button class="close" type="text" icon="el-icon-close" @click="close">关闭</el-button>
        </template>
      </FormGenerator>
    </el-drawer>
  </span>
</template>

<script>
import _ from 'lodash'
import FormGenerator from '@/components/form-generator/index.vue'
export default {
  name: 'FormGeneratorDrawer',
  components: {
    FormGenerator
  },
  data() {
    return {
      drawer: false,
      fromData: {},
      preComponents: '',
      nowComponents: []
    }
  },

  mounted() {},

  methods: {
    updateForm(data) {
      this.nowComponents = data
    },
    openDrawer(data) {
      this.drawer = true
      this.fromData = _.cloneDeep(data) ?? {}
      const components = this.fromData.components?.fields ?? []
      this.preComponents = JSON.stringify(components)
      this.nowComponents = components
      delete this.fromData.components?.fields
      this.$nextTick(() => {
        this.$refs.FormGenerator.editForm(components, this.fromData.components)
      })
    },
    close() {
      if (this.preComponents === JSON.stringify(this.nowComponents)) {
        this.drawer = false
      } else {
        this.$confirm('系统不会保存您的更改，确定要关闭吗?', '警告', {
          confirmButtonText: '关闭',
          cancelButtonText: '取消',
          confirmButtonClass: 'confirm-button-close ',
          type: 'warning'
        }).then(() => {
          this.drawer = false
        })
      }
    },
    saveFormConfig() {
      this.$refs.FormGenerator.AssembleFormData()
      this.$emit('saveFormConfig', { ...this.fromData, components: this.$refs.FormGenerator.formData })
    },
    saved() {
      this.preComponents = JSON.stringify(this.nowComponents)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-button.close {
  &:hover {
    color: red;
  }
}
.close-btn {
  color: red !important;
}
</style>
